// import { PiniaPluginContext } from 'pinia'

import type { PiniaPluginContext } from 'pinia'

// 定义插件返回的类型
interface TimeTravelPluginProperties {
  _isTimeTraveling?: boolean
  undo: () => void
  redo: () => void
  getHistory: () => any[]
  clearHistory: () => void
}

// 扩展 Pinia 类型以添加插件提供的属性和方法
declare module 'pinia' {
  export interface PiniaCustomProperties {
    // 时间旅行插件属性 - 使用联合类型保留原有属性
    _isTimeTraveling?: boolean
    undo: () => void
    redo: () => void
    getHistory: () => any[]
    clearHistory: () => void
  }
}

// 高级插件：添加时间旅行调试功能
export function timeTravelPlugin(context: PiniaPluginContext): TimeTravelPluginProperties {
  const history: any[] = []
  let historyIndex = -1

  // 保存状态历史
  const saveHistory = () => {
    const currentState = JSON.parse(JSON.stringify(context.store.$state))

    history.push(currentState)
    historyIndex = history.length - 1
  }

  // 初始化历史
  saveHistory()

  // 监听状态变化
  context.store.$subscribe(
    () => {
      // 只有在不是通过时间旅行操作时才保存历史
      if (!context.store._isTimeTraveling) {
        saveHistory()
      }
    },
    { deep: true }
  )

  return {
    // 时间旅行方法
    undo() {
      if (historyIndex > 0) {
        historyIndex--
        context.store._isTimeTraveling = true
        context.store.$patch(history[historyIndex])
        context.store._isTimeTraveling = false
      }
    },

    redo() {
      if (historyIndex < history.length - 1) {
        historyIndex++
        context.store._isTimeTraveling = true
        context.store.$patch(history[historyIndex])
        context.store._isTimeTraveling = false
      }
    },

    getHistory() {
      return [...history]
    },

    clearHistory() {
      history.length = 0
      historyIndex = -1
      saveHistory()
    }
  }
}
